package com.longcai.cm.web.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.longcai.cm.bean.R;
import com.longcai.cm.utils.DateUtils;
import com.longcai.cm.utils.FileUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

@Api(value = "上传文件相关", tags = "上传文件相关")
@ApiSort(value = 50)
@Controller
@RequestMapping("/system/common")
public class SysUploadController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Value("${lcmaster.upload.systemUploadPath}")
    private String systemUploadPath;


    @Value("${lcmaster.upload.systemUploadFilePath}")
    private String systemUploadFilePath;

    /**
     * 文件上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public R upload(HttpServletRequest request) {

        Map<String, Object> resultMap = new HashMap<>();

        try {
            String dateStr = DateUtils.getTodayStr();
            String descFileDir = systemUploadPath + dateStr;
            FileUtil.mkdirs(descFileDir);
            String dataString = "";
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");

                String newFileName = DateUtils.getTodayStr() + new Random().nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
                InputStream is = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                is.close();
                dataString = "/upload/" + dateStr + "/" + newFileName;
            }
            resultMap.put("state", "success");
            resultMap.put("path", dataString);
            return R.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("state", "fail");
        }
        return R.success(resultMap);
    }


    /**
     * 文件上传 不修改文件名称
     *
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public R uploadFile(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        Map<String, Object> resultMap = new HashMap<String, Object>();

        try {
            String descFileDir = systemUploadFilePath;
            FileUtil.mkdirs(descFileDir);
            String dataString = "";
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");
                //存储文件
                //文件名  fileNames.substring(0,split)
                //文件格式   fileNames.substring(split+1,fileNames.length())
                //文件内容 file.getBytes()
                //file.getInputStream()

                String newFileName = DateUtils.getTodayStr() + new Random().nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
                InputStream is = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                is.close();
                dataString = "/uploadFile/" + newFileName;
            }
            resultMap.put("state", "success");
            resultMap.put("path", dataString);
            return R.success(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("state", "fail");
        }
        return R.success(resultMap);
    }


    /**
     * 文件上传
     *
     * @param request
     * @param response
     * @param session
     * @return
     */
    @RequestMapping("/uploadAdmin")
    @ResponseBody
    public Map<String, Object> uploadAdmin(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            // 上传文件保存路径
            String uploadPath = systemUploadPath;
            String dateStr = DateUtils.getTodayStr();

            String descFileDir = uploadPath + dateStr;

            FileUtil.mkdirs(descFileDir);

            String dataString = "";
            String fileType = "";
            String preTarget = "width";//默认以宽度为基准进行缩放

            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());


                try {
                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream()); // 通过MultipartFile得到InputStream，从而得到BufferedImage
                    if (bufferedImage == null) {
                        // 证明上传的文件不是图片，获取图片流失败，不进行下面的操作
                        System.err.println("该文件非图片");
                    } else {
                        Integer width = bufferedImage.getWidth();
                        Integer height = bufferedImage.getHeight();
                        System.err.println("图片宽度===" + width + "----" + "图片高度===" + height);
                        System.err.println("图片宽度===" + width / 400 + "----" + "图片高度===" + height / 200);
                        System.err.println("图片宽度===" + width / height + "----" + "图片高度===" + 400 / 200);
                        //前端渲染时，判断以宽度为标准还是以高度为标准，（以较长的一边为基准进行缩放 ， 不会导致缩放时显示不全）
                        preTarget = width / 400 >= height / 200 ? "width" : "height";
                        //	preTarget = width>height?"width":"height";
                    }
                    // 省略逻辑判断
                } catch (Exception e) {
                    // 省略异常操作
                    e.printStackTrace();
                    System.err.println("文件解析异常");
                }


                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");
                //存储文件
                //文件名  fileNames.substring(0,split)
                //文件格式   fileNames.substring(split+1,fileNames.length())
                //文件内容 file.getBytes()
                //file.getInputStream()

                String newFileName = DateUtils.getTodayStr() + new Random().nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
                InputStream is = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                is.close();

                dataString = "/upload/" + dateStr + "/" + newFileName;
                fileType = fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
            }

            resultMap.put("state", "success");
            resultMap.put("path", dataString);
            resultMap.put("type", fileType); //文件类型
            resultMap.put("preTarget", preTarget);//预览时的缩放指标

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("state", "fail");
        }

        return resultMap;

    }

}
